<!DOCTYPE html>
<html lang="en">
<head>
  <title>Exception Handling - Born to build better enterprise frameworks and apps</title>
  <meta charset="utf-8">
  <meta name="description" content="index.description">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="/images/favicon.png" type="image/x-icon">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css" />
<link rel="stylesheet" href="/css/index.css">

    <script>
    !function(t,e,a,r,c){t.TracertCmdCache=t.TracertCmdCache||[],t[c]=window[c]||
      {_isInit:!0,call:function(){t.TracertCmdCache.push(arguments)},
      start:function(t){this.call('start',t)}},t[c].l=new Date;
      var n=e.createElement(a),s=e.getElementsByTagName(a)[0];
      n.async=!0,n.src=r,s.parentNode.insertBefore(n,s)}
    (window,document,'script','https://tracert.alipay.com/tracert.js','Tracert');
      Tracert.start({
        plugins: [ 'BucName' ],
        spmAPos: 'a454',
        spmBPos: 'b4893',
      });
    </script>
  
</head>
<body>
  <div class="nav" >
  <header>
    <a href="/en/" class="nav-logo leftpadding" alt="egg"><img src="https://zos.alipayobjects.com/rmsportal/VTcUYAaoKqXyHJbLAPyF.svg"></a>
    <ul class="nav-item">
      <li>
        <form id="search-form">
          <input type="text" id="search-query" class="search-query st-default-search-input">
        </form>
      </li>
      <li><a href="/en/intro/" alt="Guide">Guide</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/en/tutorials/index.html" alt="Tutorials">Tutorials</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="Plugins">Plugins</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="Release">Release</a></li>
      
      
        <li class="translations">
          <a class="nav-link">中文文档</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/core/error-handling.html" style="color: #22ab28">English</a></li><li><a id="zh-cn" href="/zh-cn/core/error-handling.html" >中文</a></li></ul>
        </li>
      
      <li><iframe src="https://ghbtns.com/github-btn.html?user=eggjs&repo=egg&type=star&count=true" frameborder="0" scrolling="0" width="150px" height="20px"></iframe></li>
    </ul>
    <a id="mobileTrigger" href="#" class="mobile-trigger">
      <ul>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </a>
  </header>
</div>
  <div id="container" class="container">
    <div class="page-main">
  <article class="markdown-body">
    <h1>Exception Handling</h1>
    <h2 id="exception-capture"><a class="markdown-anchor" href="#exception-capture">#</a> Exception Capture</h2>
<p>Taking benefits from framework asynchronous support, all exceptions can be caught by <code>try catch</code>.</p>
<p>With those features, you can take following implementation as reference:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app/service/test.js</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> res = <span class="keyword">await</span> <span class="keyword">this</span>.ctx.curl(<span class="string">'http://eggjs.com/api/echo'</span>, &#123; <span class="attr">dataType</span>: <span class="string">'json'</span> &#125;);</span><br><span class="line">  <span class="keyword">if</span> (res.status !== <span class="number">200</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'response status is not 200'</span>);</span><br><span class="line">  <span class="keyword">return</span> res.data;</span><br><span class="line">&#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">  <span class="keyword">this</span>.logger.error(err);</span><br><span class="line">  <span class="keyword">return</span> &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Generally, you can use <code>try catch</code> to catch exceptions. However, some implementations may break this mechanism down. Imaging that <code>await</code> makes generators run in order just like a chain. What will happen if one of them jumpoff the chain? The following code can help you realize the imagination:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app/controller/home.js</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="keyword">async</span> buy () &#123;</span><br><span class="line">    <span class="keyword">const</span> request = &#123;&#125;;</span><br><span class="line">    <span class="keyword">const</span> config = <span class="keyword">await</span> ctx.service.trade.buy(request);</span><br><span class="line">    <span class="comment">// checking the deal and don't block current request</span></span><br><span class="line">    setImmediate(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      ctx.service.trade.check(request).catch(<span class="function"><span class="params">err</span> =&gt;</span> ctx.logger.error(err));</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>In this case, you may find that the exceptions in <code>setImmediate</code> will be swallowed because the scope breaks the chain, although egg already handled exceptions externally.</p>
<p>Above scene is also considered. To catch the exception inside the scope, You can invoke helper method <code>ctx.runInBackground(scope)</code> to wrap the chain back. Now, the exceptions will be detected and caught.</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="keyword">async</span> buy () &#123;</span><br><span class="line">    <span class="keyword">const</span> request = &#123;&#125;;</span><br><span class="line">    <span class="keyword">const</span> config = <span class="keyword">await</span> ctx.service.trade.buy(request);</span><br><span class="line">    <span class="comment">// checking the deal and don't block current request</span></span><br><span class="line">    ctx.runInBackground(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">      <span class="comment">// Exceptions thrown here will be caught in background and printed into log.</span></span><br><span class="line">      <span class="keyword">await</span> ctx.service.trade.check(request);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>For convenience of locating problems, exceptions must be guaranteed to be Error object or object based on Error object, which offers a trace of which functions were called.</p>
<h2 id="egg-takes-charge-of-exceptions"><a class="markdown-anchor" href="#egg-takes-charge-of-exceptions">#</a> Egg takes charge of exceptions</h2>
<p><a href="https://github.com/eggjs/egg-onerror" target="_blank" rel="noopener">egg-onerror</a>, one of Egg's plugin, handles all exceptions thrown in Middleware, Controller and Service, and returns the error as response based on &quot;Accept&quot; in request header field.</p>
<table>
<thead>
<tr>
<th>Accept</th>
<th>ENV</th>
<th>errorPageUrl</th>
<th>response</th>
</tr>
</thead>
<tbody>
<tr>
<td>HTML &amp; TEXT</td>
<td>local &amp; unittest</td>
<td>-</td>
<td>onerror built-in error page</td>
</tr>
<tr>
<td>HTML &amp; TEXT</td>
<td>others</td>
<td>YES</td>
<td>redirect to errorPageUrl</td>
</tr>
<tr>
<td>HTML &amp; TEXT</td>
<td>others</td>
<td>NO</td>
<td>onerror built-in error page(simple, not recommended)</td>
</tr>
<tr>
<td>JSON &amp; JSONP</td>
<td>local &amp; unittest</td>
<td>-</td>
<td>JSON Object or JSONP response body with details</td>
</tr>
<tr>
<td>JSON &amp; JSONP</td>
<td>others</td>
<td>-</td>
<td>JSON object  or JSONP response body without details</td>
</tr>
</tbody>
</table>
<h3 id="errorpageurl"><a class="markdown-anchor" href="#errorpageurl">#</a> errorPageUrl</h3>
<p>Redirecting to your customized error page by setting <code>errorPageUrl</code> in <code>onerror</code> plugin.</p>
<p><code>onerror</code> config in <code>config/config.default.js</code>:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  onerror: &#123;</span><br><span class="line">    errorPageUrl: <span class="string">'/50x.html'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="create-your-universal-exception-handler"><a class="markdown-anchor" href="#create-your-universal-exception-handler">#</a> Create your universal exception handler</h2>
<p>Once the default handler no longer meet your needs, you still can customize your owner error handler by onerror's configurations.</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/config.default.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  onerror: &#123;</span><br><span class="line">    all(err, ctx) &#123;</span><br><span class="line">      <span class="comment">// Define an error handler for all type of Response.</span></span><br><span class="line">      <span class="comment">// Once config.all present, other type of error handers will be ignored.</span></span><br><span class="line">      ctx.body = <span class="string">'error'</span>;</span><br><span class="line">      ctx.status = <span class="number">500</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    html(err, ctx) &#123;</span><br><span class="line">      <span class="comment">// html hander</span></span><br><span class="line">      ctx.body = <span class="string">'&lt;h3&gt;error&lt;/h3&gt;'</span>;</span><br><span class="line">      ctx.status = <span class="number">500</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    json(err, ctx) &#123;</span><br><span class="line">      <span class="comment">// json hander</span></span><br><span class="line">      ctx.body = &#123; <span class="attr">message</span>: <span class="string">'error'</span> &#125;;</span><br><span class="line">      ctx.status = <span class="number">500</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    jsonp(err, ctx) &#123;</span><br><span class="line">      <span class="comment">// Generally, we don't need to customize jsonp error handler.</span></span><br><span class="line">      <span class="comment">// It will call json error handler and wrap to jsonp type response.</span></span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="404"><a class="markdown-anchor" href="#404">#</a> 404</h2>
<p>Egg won't take <code>NOT FOUND</code> from back-end as exception. Instead, if <code>NOT FOUND</code> is emitted without a body, it will return the following JSON object as default response.</p>
<p>identified as JSON:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"message"</span>: <span class="string">"Not Found"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>identified as HTML:</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>404 Not Found<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>Overriding default 404 page to the one you want:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/config.default.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  notfound: &#123;</span><br><span class="line">    pageUrl: <span class="string">'/404.html'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="customize-404-response"><a class="markdown-anchor" href="#customize-404-response">#</a> Customize 404 Response</h3>
<p>If you want a customized 404 response, you only need to create a middleware to handle it once, just like handling exceptions above.</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app/middleware/notfound_handler.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">notFoundHandler</span>(<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">await</span> next();</span><br><span class="line">    <span class="keyword">if</span> (ctx.status === <span class="number">404</span> &amp;&amp; !ctx.body) &#123;</span><br><span class="line">      <span class="keyword">if</span> (ctx.acceptJSON) &#123;</span><br><span class="line">        ctx.body = &#123; <span class="attr">error</span>: <span class="string">'Not Found'</span> &#125;;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ctx.body = <span class="string">'&lt;h1&gt;Page Not Found&lt;/h1&gt;'</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>Adding yours to <code>middleware</code> in config:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/config.default.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  middleware: [ <span class="string">'notfoundHandler'</span> ],</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

  </article>
  <aside id="mobileAside" class="toc">
  <div class="mobile-menu">
    <ul>
      <li><a href="/en/intro/" alt="Guide">Guide</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/en/tutorials/index.html" alt="Tutorials">Tutorials</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="Plugins">Plugins</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="Release">Release</a></li>
      
      
        <li class="translations">
          <a class="nav-link">中文文档</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/core/error-handling.html" style="color: #22ab28">English</a></li><li><a id="zh-cn" href="/zh-cn/core/error-handling.html" >中文</a></li></ul>
        </li>
      
    </ul>
  </div>
  <dl><dt id="title-Intro" style="cursor: pointer;" class="aside-title">Guide<a id="collapse-icon-Intro" class="icon opend"></a></dt><dd id=panel-Intro><ul><li><a href="/en/intro/index.html" class="menu-link">What is Egg?</a></li><li><a href="/en/intro/egg-and-koa.html" class="menu-link">Egg and Koa</a></li><li><a href="/en/intro/quickstart.html" class="menu-link">Quick Start</a></li><li><a href="/en/tutorials/progressive.html" class="menu-link">Progressive</a></li><li><a href="/en/migration.html" class="menu-link">Migration to 2.x</a></li></ul></dd><dt id="title-Basics" style="cursor: pointer;" class="aside-title">Basis Function<a id="collapse-icon-Basics" class="icon opend"></a></dt><dd id=panel-Basics><ul><li><a href="/en/basics/structure.html" class="menu-link">Directory Structure</a></li><li><a href="/en/basics/objects.html" class="menu-link">Built-in Objects</a></li><li><a href="/en/basics/env.html" class="menu-link">Environment</a></li><li><a href="/en/basics/config.html" class="menu-link">Configuration</a></li><li><a href="/en/basics/middleware.html" class="menu-link">Middleware</a></li><li><a href="/en/basics/router.html" class="menu-link">Router</a></li><li><a href="/en/basics/controller.html" class="menu-link">Controller</a></li><li><a href="/en/basics/service.html" class="menu-link">Service</a></li><li><a href="/en/basics/plugin.html" class="menu-link">Plugin</a></li><li><a href="/en/basics/schedule.html" class="menu-link">Schedule</a></li><li><a href="/en/basics/extend.html" class="menu-link">Extend</a></li><li><a href="/en/basics/app-start.html" class="menu-link">Custom Init</a></li></ul></dd><dt id="title-Core" style="cursor: pointer;" class="aside-title">Core<a id="collapse-icon-Core" class="icon opend"></a></dt><dd id=panel-Core><ul><li><a href="/en/core/development.html" class="menu-link">Development</a></li><li><a href="/en/core/unittest.html" class="menu-link">Unit Testing</a></li><li><a href="/en/core/deployment.html" class="menu-link">Deployment</a></li><li><a href="/en/core/logger.html" class="menu-link">Logger</a></li><li><a href="/en/core/httpclient.html" class="menu-link">HttpClient</a></li><li><a href="/en/core/cookie-and-session.html" class="menu-link">Cookie and Session</a></li><li><a href="/en/core/cluster-and-ipc.html" class="menu-link">Cluster and IPC</a></li><li><a href="/en/core/view.html" class="menu-link">View</a></li><li><a href="/en/core/error-handling.html" class="menu-link">Error Handling</a></li><li><a href="/en/core/security.html" class="menu-link">Security</a></li><li><a href="/en/core/i18n.html" class="menu-link">i18n</a></li></ul></dd><dt id="title-Tutorials" style="cursor: pointer;" class="aside-title">Tutorials<a id="collapse-icon-Tutorials" class="icon opend"></a></dt><dd id=panel-Tutorials><ul><li><a href="/en/tutorials/mysql.html" class="menu-link">MySQL</a></li><li><a href="/en/tutorials/restful.html" class="menu-link">RESTful API</a></li><li><a href="/en/tutorials/passport.html" class="menu-link">Passport</a></li><li><a href="/en/tutorials/socketio.html" class="menu-link">Socket.IO</a></li><li><a href="/en/tutorials/assets.html" class="menu-link">Assets</a></li><li><a href="/en/tutorials/typescript.html" class="menu-link">TypeScript</a></li></ul></dd><dt id="title-Advanced" style="cursor: pointer;" class="aside-title">Advanced<a id="collapse-icon-Advanced" class="icon opend"></a></dt><dd id=panel-Advanced><ul><li><a href="/en/advanced/loader.html" class="menu-link">Loader</a></li><li><a href="/en/advanced/plugin.html" class="menu-link">Plugin Development</a></li><li><a href="/en/advanced/framework.html" class="menu-link">Framework</a></li><li><a href="/en/advanced/cluster-client.html" class="menu-link">Cluster Enhancement</a></li><li><a href="/en/advanced/view-plugin.html" class="menu-link">View Plugin</a></li><li><a href="/en/style-guide.html" class="menu-link">Style Guide</a></li></ul></dd><dt id="title-Community" style="cursor: pointer;" class="aside-title">Community<a id="collapse-icon-Community" class="icon opend"></a></dt><dd id=panel-Community><ul><li><a href="/en/plugins/" class="menu-link">Plugin List</a></li><li><a href="/en/contributing.html" class="menu-link">Contributing</a></li><li><a href="/en/resource.html" class="menu-link">Resource</a></li><li><a href="/en/faq.html" class="menu-link">FAQ</a></li></ul></dd></dl>
</aside>
<script>
var mobileTrigger = document.getElementById('mobileTrigger');
var mobileAside = document.getElementById('mobileAside');

var expandMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon opend';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = '';
  }
}

var collapseMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon closed';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = 'aside-panel-hidden';
  }
}

mobileAside.onclick = function(e) {
  const targetId = e.target.id;
  if (targetId && (targetId.indexOf('title-') > -1 || targetId.indexOf('collapse-icon-') > -1)) {
    const title = targetId.replace('title-', '').replace('collapse-icon-', '');
    try { 
      // the the browser may have no localStroage or JSON.parse may throw exception.
      const menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
        
      // current menu status
      const curClosed = menuInfo[title] ? menuInfo[title].closed : false; // default false

      // change UI
      curClosed ? expandMenu(title) : collapseMenu(title);

      // save menuInfo to localStorage
      menuInfo[title] = { closed: !curClosed } // opposite
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    } catch (e) {}
  }
};

mobileTrigger.onclick = function(e) {
  e.preventDefault();
  if (mobileAside.className.indexOf('mobile-show') === -1) {
    mobileAside.className += ' mobile-show';
  } else {
    mobileAside.className = 'toc';
  }
};

(function() {
  // save data to localStorage because the page will refresh when user change the url.
  let menuInfo;
  try { 
    // the the browser may have no localStroage or JSON.parse may throw exception.
    menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
    if (!menuInfo) {
      menuInfo = {};
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    }
  } catch (e) {
    menuInfo = {}; // default {}
  }

  for (const title in menuInfo) {
    if (menuInfo[title] && menuInfo[title].closed) { // menu in closed status.
      collapseMenu(title);
    } else {
      expandMenu(title);
    }
  }

  // highlight menu
  const pathname = window.location.pathname;
  const selector = `a[href="${pathname}"].menu-link,a[href="${pathname}index.html"].menu-link`;
  const menuItem = mobileAside.querySelector(selector);
  if (menuItem) { menuItem.className += ' highlight'; }
})();
</script>

</div>

  </div>
</body>
<script src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js"></script>
<script>
docsearch({
  apiKey: '1561de31a86f79507ea00cdb54ce647c',
  indexName: 'eggjs',
  inputSelector: '#search-query',
});
</script>
<div class="cnzz">
<script src="https://s11.cnzz.com/z_stat.php?id=1261142226&web_id=1261142226" language="JavaScript"></script>
</div>

</html>
